package mq

import (
	"container/list"
	"encoding/json"
	"github.com/Shopify/sarama"
)

const (
	OrderCancel ="matching-order-cancel"
	OrderTrade ="matching-order-trade"
	OrderCompleted ="matching-order-completed"
)

type MessageInfo struct {
	Topic string		`json:"topic"`
	Code int			`json:"code"`
	OrderId string		`json:"orderId"`
	Message string		`json:"message"`
	Data interface{}	`json:"data"`
}
func (messageInfo *MessageInfo) ToJson() string {
	data, err := json.Marshal(messageInfo)
	if err!=nil {
		return string(data)
	}else {
		return ""
	}
}


var Producer sarama.AsyncProducer

func Init() {
	/*addr := conf.GetString("kafka.addr")
	port := conf.GetString("kafka.port")
	config := sarama.NewConfig()
	config.Producer.RequiredAcks = sarama.WaitForAll
	config.Producer.Partitioner = sarama.NewRandomPartitioner
	config.Producer.Return.Successes = false
	config.Producer.Return.Errors = false
	config.Version = sarama.V0_11_0_2

	producer, err := sarama.NewAsyncProducer([]string{addr+":"+port}, config)
	Producer=producer
	if err != nil &&producer!=nil{
		//panic(err)
	} else {
		log.Infof("Connected to kafka: %s success", addr+":"+port)
	}*/
}

func SendMsg(topic string,content string)  {
	// send message
	/*msg := &sarama.ProducerMessage{
		Topic: topic,
		Key:   sarama.StringEncoder("go_test"),
	}

	value := content
	msg.Value = sarama.ByteEncoder(value)
	// send to chain
	Producer.Input() <- msg*/
	/*select {
	case suc := <-Producer.Successes():
		log.Infof("kafka producer send success,%s",suc.Topic)
	case fail := <-Producer.Errors():
		log.Errorf("kafka producer find error :%s",fail.Err.Error())
	}*/
}

//撤单
func SendOrderCancelMsg(flag bool,orderId string)  {
	code:=0
	mes:="success"
	if !flag {
		code=1
		mes="cancel fail"
	}
	messageInfo :=MessageInfo{
		OrderCancel,
		code,
		orderId,
		mes,
		nil,
	}
	SendMsg(OrderCancel,messageInfo.ToJson())
}

// 成交
func SendOrderTradeMsg(trades *list.List)  {

	messageInfo :=MessageInfo{
		OrderTrade,
		0,
		"",
		"success",
		trades,
	}
	SendMsg(OrderTrade,messageInfo.ToJson())
}

// 订单完成
func SendOrderCompletedMsg(orders *list.List)  {
	messageInfo :=MessageInfo{
		OrderCompleted,
		0,
		"",
		"success",
		orders,
	}
	SendMsg(OrderCompleted,messageInfo.ToJson())
}
